/*
 * Copyright (C) 2012 Rothens
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package rpg.inventory;

import java.util.Arrays;
import java.util.LinkedList;
import rpg.entities.Entity;

/**
 * rothens.tumblr.com
 *
 * @author Rothens
 */
public class Inventory {

    private Item[] items;
    private int capacity;

    public Inventory(int capacity) {
        items = new Item[capacity];
        this.capacity = capacity;
    }

    public boolean hasItem(String name) {
        for (Item i : items) {

            if (i.name.equalsIgnoreCase(name)) {

                return true;
            }
        }

        return false;
    }
    
    public boolean hasItem(int itemID) {
        for (Item i : items) {
            if (i.itemID == itemID) {
                return true;
            }
        }
        return false;
    }

    public boolean consume(String name, Entity e) {
        if (!hasItem(name)) {
            return false;
        }
        for(int i = 0; i < items.length; i++){
            if(items[i] == null) continue;
            if(items[i].name.equalsIgnoreCase(name)){
                if(!items[i].consume(e)){
                    items[i] = null;
                }
                return true;
            }
        }
        return false;
    }

    public boolean addItem(Item item, Entity e) {
        LinkedList<Integer> emptySpaces = new LinkedList<Integer>();
        
        //search for existing item in the same type
        for(int i = 0; i < items.length; i++){
            if(items[i] == null){
                emptySpaces.add(i);
                continue;
            }
            if(items[i].itemID == item.itemID){
                item.quantity = items[i].aquire(item.quantity, e);
                if(item.quantity == 0) return true; //succesfully added the item
            }            
        }
        //not found, so we put it in the first empty slot
        if(emptySpaces.isEmpty()) return false;
        try {
            items[emptySpaces.getFirst()] = (Item) item.clone();
        } catch (CloneNotSupportedException cnse){
            System.out.println(cnse.getMessage());
        }
        return true;
    }

    public Item getItem(String name) {
        for(Item i : items){
            if(i.name.equalsIgnoreCase(name)){
                return i;
            }
        }

        return null;
    }
}
